package com.hileto.inf.actions.filters;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Repository;
import org.springframework.web.filter.OncePerRequestFilter;

import com.hileto.inf.actions.methods.BaseMethod;
import com.hileto.inf.actions.methods.params.SysParam;
import com.hileto.inf.utils.JsonHelp;

@Repository("restFilter")
public class RestFilter extends OncePerRequestFilter {
	private static final long serialVersionUID = 1L;
	private static Map<String,BaseMethod<?>> methodMapping = new HashMap<String, BaseMethod<?>>();
	
    public RestFilter() {
    }
    
    public final synchronized void registerMethod(String methodName, BaseMethod<?> baseMethod) {
		methodMapping.put(methodName, baseMethod);
	}
	
	public void responseJson(HttpServletResponse response,String content, String type) {
		try {
			response.setContentType(type + ";charset=UTF-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.getWriter().write(content);
			response.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String doHttpProcess(String method,HttpServletRequest request,
			HttpServletResponse response) {
		String result = null;
		result = JsonHelp.object2Json("method["+method+"] is not found! ");
		return result;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		SysParam sysParam = new SysParam(request);
		BaseMethod<?> methodObject = methodMapping.get(sysParam.getMethod());
		String result = null;
		if(null != methodObject){
			result = methodObject.doHttpProcess(sysParam,request);
		}else{
			result = this.doHttpProcess(sysParam.getMethod(),request,response);
		}
		responseJson(response, result, "text/html");
	}
}
